package org.brisling.medical.queryService;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.exception.DangerousOperatorException;
import org.brisling.common.util.DateUtil;
import org.brisling.medical.domain.MedicalDoubleThree;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * <p>Title: QueryMedicalDoubleThreeService</p>
 * <p>Description: 抗菌药物使用率查询service</p>
 * <p>Company: tongking</p>
 * @author trastor
 * @since 1.0
 * @version 1.0
 * @date 2016年7月20日 下午10:01:49
 */
@RestController
@RequestMapping("/medicaldoublethree/query")
public class QueryMedicalDoubleThreeService extends AbstractBaseQueryService<MedicalDoubleThree>{
	
//	@Autowired
//	private MedicalDoubleThreeService medicalDoubleThreeService;
	
	@Autowired
	private QueryDictionaryService qryDictionaryService;
	
	@Autowired
	private ShiroSecurityService shiroSecurityService;
	
	public QueryMedicalDoubleThreeService(){
		this.moduleName = ConstSysParam.MODULE_DOUBLE_THREE;
		this.subSystem = ConstSysParam.SUBSYSTEM_MEDICAL;
		this.tableName = this.moduleName;
		this.clazz = MedicalDoubleThree.class;
		typeMap = this.getTypeMap(clazz);
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/popPage.action")
	public ModelAndView getPopPage(){
		String userid = shiroSecurityService.getCurrentUserIdentify();
		String _page = "popMain";
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			if(!isManageJob(userid)){				
				_page="popDetail";
			}					
		}
		return new ModelAndView("/medical/medical_anti_medicals/"+_page);
	}
	@RequestMapping("/getListDomain.action")
	public ListDomain<MedicalDoubleThree> getListDomain(@RequestBody(required=false) String body){		
		
		Map<String,Object> map = this.getBodyParam(body);
		String userid = shiroSecurityService.getCurrentUserIdentify();
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){			
			addJobDeptConditionToMap(userid,map,"dept_code");			
			//查找科室数据		
		}
		//查询表
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
		
	}
	
	/**
	 * 获取部门统计指标
	 * @param body
	 * @return
	 */
	@RequestMapping("/getDeptListDomain.action")
	public ListDomain<MedicalDoubleThree> getDeptListDomain(@RequestBody(required=false) String body){		
		
		Map<String,Object> map = this.getBodyParam(body);
		
		String userid = shiroSecurityService.getCurrentUserIdentify();
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			if(isManageJob(userid)){
				addJobDeptConditionToMap(userid,map,"dept_code");
			}else{
				addUsridConditionToMap(userid,map,"doct_code");
			}				
			//查找科室数据		
		}
		
		Map<String,String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		if(!paramMap.containsKey("data_type"))
			paramMap.put("data_type", "1");
		
		if(!paramMap.containsKey("patient_type"))
			paramMap.put("patient_type", "1");
		map.put(ConstSysParam.CONDITION_MAP_KEY, paramMap);
		//查询表
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
	}
	
	/**
	 * 获取部门统计指标
	 * @param body
	 * @return
	 */
	@RequestMapping("/getAllListDomain.action")
	public ListDomain<MedicalDoubleThree> getAllListDomain(@RequestBody(required=false) String body){		
		
		Map<String,Object> map = this.getBodyParam(body);
		
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			if(isManageJob(userid)){
				String deptids = this.getJobDeptidAndAccountDeptids(userid);
				paramMap.put("dept_code_in", deptids);
			}else{
				
				paramMap.put("doct_code", userid);
			}
			//查找科室数据		
		}else{
			paramMap.put("dept_code_in", "-1");
		}		
		map.put(ConstSysParam.CONDITION_MAP_KEY, paramMap);
		//查询表
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
	}
	
	/**
	 * 获取部门统计指标
	 * @param body
	 * @return
	 */
	
	private List<MedicalDoubleThree> getList(String monitor_year_month){
		
		String sql = String.format("select * from %1$s where monitor_year_month='%2$s'",this.tableName,monitor_year_month); 
		//查询表
		return super.getAllList(sql);
		
	}
	
	/**
	 * 查询实时数据
	 * @param body
	 * @return
	@RequestMapping("/getRealTimeListDomain.action")
	public ListDomain<MedicalDoubleThree> getRealTimeListDomain(@RequestBody(required=false) String body){		
		Map<String,Object> paramMap = this.getBodyParam(body);
		
		String[] monitorDate = super.getMonitorDate(paramMap);
		if(monitorDate!=null && monitorDate.length>1){			
			
			String start = monitorDate[0];
			String end = monitorDate[1];
			String year_month = monitorDate[2];
			List<MedicalDoubleThree> inlists =countMedicalInpatient (year_month,start,end,null);
			List<MedicalDoubleThree> outlists =countMedicalOutpatient(year_month,start, end);
			
			if(inlists!=null || outlists!=null){
				inlists.addAll(outlists);
				medicalDoubleThreeService.save(inlists);
				return super.getListDomainByConditionAndOrderUseTable(body, typeMap, orderMap,true);
			}					
			
		}
		//查询表
		
		return new ListDomain<MedicalDoubleThree>();
	}
	 */
	
	
	public void autoTask(Integer year,Integer month){
		this.autoMonitor(year, month);
		this.autoUpdateStandard(year, month);
	}
	/**
	 * 执行自动统计
	 * @return 
	 */
	public List<MedicalDoubleThree> autoMonitor(Integer year,Integer month){
		String[] yestodayMonth = null;
		if(year ==null || month ==null)
			yestodayMonth = DateUtil.getYestodayMonthDay();
		else{
			yestodayMonth = DateUtil.getMonthDay(year, month);
		}
		List<MedicalDoubleThree> inlists = countMedicalInpatient(yestodayMonth[2],yestodayMonth[0],yestodayMonth[1],null);

		List<MedicalDoubleThree> outlists =countMedicalOutpatient(yestodayMonth[2],yestodayMonth[0],yestodayMonth[1]);
		
		List<MedicalDoubleThree> outEmrlists =countMedicalOutEmrpatient(yestodayMonth[2],yestodayMonth[0],yestodayMonth[1]);
		
		//查询已有数据
		List<MedicalDoubleThree> oldLists = this.getList(yestodayMonth[2]);
		LinkedHashMap<String,MedicalDoubleThree> lmap = new LinkedHashMap<String,MedicalDoubleThree>();
		
		//将已有值存入临时map
		if(oldLists!=null && oldLists.size()>0){
			
			for(int i=0;i<oldLists.size();i++){
				MedicalDoubleThree b = oldLists.get(i);
				String _key = null;
				if(b.getDept_code() == null){
					continue;
				}
				if(b.getDoct_code()==null ){
					_key = b.getDept_code().toString() + "-" +b.getPatient_type();
				}else{
					_key = b.getDept_code() +"-" + b.getDoct_code() +"-"+b.getPatient_type();
				}
				lmap.put(_key, b);
			}
		}
		
		
		if(inlists!=null || outlists!=null || outEmrlists != null){
			inlists.addAll(outlists);
			inlists.addAll(outEmrlists);
			if(lmap!=null && lmap.size()>0){
				for(int i=0;i<inlists.size();i++){
					MedicalDoubleThree b = inlists.get(i);
					if(b.getDept_code() == null || b.getPatient_type() == null){
						continue;
					}
					String _key = null;
					if(b.getDoct_code()==null ){
						_key = b.getDept_code().toString() + "-" +b.getPatient_type();
					}else{
						_key = b.getDept_code() +"-" + b.getDoct_code() +"-"+b.getPatient_type();
					}
					if(lmap.containsKey(_key)){
						inlists.get(i).setId(lmap.get(_key).getId());
					}
					System.out.println(i);
				}
			}
			
//			medicalDoubleThreeService.save(inlists);			
		}
		return inlists;
	}
	
	private List<MedicalDoubleThree> countMedicalOutEmrpatient(String year_month, String startDate, String endDate) {
		String[] sqlids = {"anti_medical_all_outEmrpatient","anti_medical_dept_outEmrpatient","anti_medical_doct_outEmrpatient"};
		//统计全院数据-住院
		
		List<String> sqls = new ArrayList<String>();
		for(int i = 0;i<sqlids.length;i++){
			String sql = qryDictionaryService.getSqlByBizcode(sqlids[i]);
			if(sql!=null){
				sqls.add(sql);
			}
		}
		//所有数据
		return super.monitorCountBase(year_month,startDate,endDate,sqls);	
	}

	public String autoUpdateStandard(Integer year,Integer month){
		String[] yestodayMonth = null;
		if(year ==null || month ==null)
			yestodayMonth = DateUtil.getYestodayMonthDay();
		else{
			yestodayMonth = DateUtil.getMonthDay(year, month);
		}
//		medicalDoubleThreeService.updateStandard(yestodayMonth[2]);
		return yestodayMonth[2];
	}
	/**
	 * 统计住院患者抗菌药物使用情况
	 * @param year_month
	 * @param startDate
	 * @param endDate
	 * @param countType	0,期间出院病人;1,期间在院病人
	 * @return
	 */
	public List<MedicalDoubleThree> countMedicalInpatient(String year_month,String startDate ,String endDate,String countType){
		
		
		//出院病人
		String _count_type = "0";
		
		//在院病人统计语句
		String[] sqlins= {"anti_medical_all_inpatient_in","anti_medical_dept_inpatient_in","anti_medical_doct_inpatient_in"};
		
		//在院病人统计语句
		String[] sqlouts= {"anti_medical_all_inpatient_out","anti_medical_dept_inpatient_out","anti_medical_doct_inpatient_out"};
		_count_type = countType==null?_count_type:countType;
		
		String[] sqlids = null;
		
		if(_count_type.compareTo("0")==0){			
			sqlids = sqlouts;
		}else{
			sqlids = sqlins;
		}
		//统计全院数据-住院
		
		List<String> sqls = new ArrayList<String>();
		for(int i = 0;i<sqlids.length;i++){
			String sql = qryDictionaryService.getSqlByBizcode(sqlids[i]);
			if(sql!=null){
				sqls.add(sql);
			}
		}
		//所有数据
		List<MedicalDoubleThree> lists = super.monitorCountBase(year_month,startDate,endDate,sqls);		
		
		return lists;
		
	}
	
	/**
	 * 统计基本药物门诊缓存信息
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public List<MedicalDoubleThree> countMedicalOutpatient(String year_month,String startDate ,String endDate){
		
			
		
		String[] sqlids = {"anti_medical_all_outpatient","anti_medical_dept_outpatient","anti_medical_doct_outpatient"};
		//统计全院数据-住院
		
		List<String> sqls = new ArrayList<String>();
		for(int i = 0;i<sqlids.length;i++){
			String sql = qryDictionaryService.getSqlByBizcode(sqlids[i]);
			if(sql!=null){
				sqls.add(sql);
			}
		}
		//所有数据
		return super.monitorCountBase(year_month,startDate,endDate,sqls);	
		
	}
	
	
	
	/**
	 * 根据用户id查找用户信息
	 * @param id	用户id
	 * @return 用户信息记录 
	 */
	@RequestMapping("/getOne.action")
	public MedicalDoubleThree getOne(@RequestParam(value="id",required=false) Long id){
				
		return super.getOne(id);
	}
	
	/**
	 * 根据用户唯一编码查找用户信息
	 * @param identify	用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public MedicalDoubleThree getOneByIdentify(@RequestParam(value="identify",required=false) String identify){	
		return super.getOneByIdentify(identify);
	}

	
	//MedicalDoubleThree
	/**
	 * 医疗服务统计信息异常数据
	 * @return
	 */	
	
	public List<MedicalDoubleThree> getMedicalDoubleThreeAbnormal(){		
		
		String sql = qryDictionaryService.getSqlByBizcode("anti_medical");	
		if(sql == null || sql.length() < 1){
			sql = new String("select * from medical_anti_medicals where data_type = 2 and ANTI_PERCENT is not null and AMOUNT_PERCENT_STANDARD is not null and anti_percent > amount_percent_standard and monitor_year_month = '%1$s'");
		}
		sql = String.format(sql, DateUtil.getYestodayMonthDay()[2]);
		//System.out.println(sql);
		try {
			return super.getClassedAllList(sql, MedicalDoubleThree.class);
		} catch (DangerousOperatorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 	
		return null;
	}
	
}
